import * as permissionService from "../services/permission.service";
import { Request, Response } from "express";
import { ResponseUtil } from "../utils/response.util";

export const getAllPermissions = async (req: Request, res: Response) => {
  try {
    const page = Number(req.query.page);
    const pageSize = Number(req.query.pageSize);
    const options = req.body;
    const permissions = await permissionService.getAllPermissions(
      page,
      pageSize,
      options
    );
    ResponseUtil.success(res, permissions);
  } catch (err) {
    ResponseUtil.error(res, err, "获取权限失败");
  }
};

export const getPermissinoById = async (req: Request, res: Response) => {
  try {
    const id = parseInt(req.params.id);
    const permission = await permissionService.getPermissionById(id);
    ResponseUtil.success(res, permission);
  } catch (err) {
    ResponseUtil.error(res, err, "查询权限失败");
  }
};

export const createPermission = async (req: Request, res: Response) => {
  try {
    const data = req.body;
    const newPermission = await permissionService.createPermission(data);
    ResponseUtil.success(res, newPermission);
  } catch (err) {
    ResponseUtil.error(res, err, "创建权限失败");
  }
};

export const updatePermission = async (req: Request, res: Response) => {
  try {
    const id = parseInt(req.params.id);
    const data = req.body;
    const updated = await permissionService.updatePermission(id, data);
    ResponseUtil.success(res, updated);
  } catch (err) {
    ResponseUtil.error(res, err, "更新权限失败");
  }
};

export const deletePermission = async (req: Request, res: Response) => {
  try {
    const id = parseInt(req.params.id);
    const deleteOne = await permissionService.deletePermission(id);
    ResponseUtil.success(res, deleteOne);
  } catch (err) {
    ResponseUtil.error(res, err, "删除权限失败");
  }
};
